package LeetCode_17_14;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/3/27 14:06
 * 面试题 17.14. 最小K个数
 */
public class Solution {
    public int[] smallestK(int[] arr, int k) {
        int[] res = new int[k];
        if (k==0){
            return res;
        }

        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        for (int i = 0; i < k; i++) {
            queue.offer(arr[i]);
        }

        for (int i = k; i < arr.length; i++) {
            if (arr[i]<queue.peek()){
                queue.poll();
                queue.offer(arr[i]);
            }
        }

        for (int i = 0; i < k; i++) {
           res[i]= queue.poll();
        }

        return res;
    }
}